﻿/*
Copyright (C) 2011, Cardon Fry.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
*/

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using eBookInfoGrabber.Properties;

namespace eBookInfoGrabber
{
    class InformationGrabing
    {
        public static WebResponse Response;
        public static Stream Stream;
        public static StreamReader Reader;
        string[] _result;
        string _eBookUrl;
        public bool Passed;
        private string _fileContent;
        private static OpenFileDialog _fDialog;

        public void GetTemplate()
        {
            _fDialog = new OpenFileDialog
                                         {
                                             Title = Resources.OpenTxtFile,
                                             Filter = Resources.OnlyTextFiles,
                                             InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath),
                                             CheckFileExists = true
                                         };

            if (_fDialog.ShowDialog() != DialogResult.OK) return;

        }

        public void CheckUpdate()
        {
            const string url = "http://ebookinfograbber.codeplex.com/";
            var request =
                               (HttpWebRequest)WebRequest.Create(url);
            request.UserAgent =
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; " +
"Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; " +
".NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; " +
"InfoPath.2; OfficeLiveConnector.1.3; OfficeLivePatch.0.0)";

            Response = request.GetResponse();
            Stream = Response.GetResponseStream();
            Reader = new StreamReader(Stream);

            var versionSearch = Reader.ReadToEnd();

            _result = GetStringInBetween("<td id=\"ReleaseName\" class=\"ActivityData\">eBookInfoGrabber - Stand Alone Version ", "</td>", versionSearch, false, false);
            var versionCheck = Convert.ToDouble(_result[0]);
            const double version = 1.3;

            if (version >= versionCheck) return;
            var dialogResult = MessageBox.Show(Resources.ThereIsAnUpdateAvailable, Resources.UpadteAvailable, MessageBoxButtons.YesNo);

            if (dialogResult != DialogResult.Yes) return;
            System.Diagnostics.Process.Start("http://ebookinfograbber.codeplex.com/");
            Application.Exit();
        }

        public static string[] GetStringInBetween(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd)
        {
            string[] result = { "", "" };
            int iIndexOfBegin = strSource.IndexOf(strBegin);
            if (iIndexOfBegin != -1)
            {
                if (includeBegin)
                { iIndexOfBegin -= strBegin.Length; }
                strSource = strSource.Substring(iIndexOfBegin
                    + strBegin.Length);
                int iEnd = strSource.IndexOf(strEnd);

                if (iEnd != -1)
                {
                    if (includeEnd)
                    { iEnd += strEnd.Length; }
                    result[0] = strSource.Substring(0, iEnd);
                    if (iEnd + strEnd.Length < strSource.Length)
                    { result[1] = strSource.Substring(iEnd + strEnd.Length); }
                }
            }
            else
            { result[1] = strSource; }
            return result;
        }

        public string StripHtml(string str)
        {
            string strippedString;
            try
            {
                //replace all HTML tags
                strippedString = Regex.Replace(str, "<.*?>", string.Empty);
            }
            catch
            {
                strippedString = string.Empty;
            }
            return strippedString;
        }

        public string StripNewLine(string str)
        {
            string strippedString;
            try
            {
                strippedString = Regex.Replace(str, "(\n|\r)+", string.Empty);
            }
            catch
            {
                strippedString = string.Empty;
            }
            return strippedString;
        }

        public void GetBook(string isbn)
        {
            isbn = isbn.Replace("-", "");
            var url = "http://ebookstore.sony.com/search?keyword=" + isbn;

            if (url != "http://ebookstore.sony.com/search?keyword=")
            {
                var request =
                               (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent =
    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; " +
    "Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; " +
    ".NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; " +
    "InfoPath.2; OfficeLiveConnector.1.3; OfficeLivePatch.0.0)";

                Response = request.GetResponse();
                Stream = Response.GetResponseStream();
                Reader = new StreamReader(Stream);

                var eBookSearch = Reader.ReadToEnd();

                if (eBookSearch.Contains("<div class=\"warning\">"))
                {
                    MessageBox.Show(Resources.CouldNotFindEbookPleaseCheckIfSuppliedIsbnIsCorrect);
                    return;
                }

                _result = GetStringInBetween("<h3 class=\"item\">", "class=\"fn\">", eBookSearch, false, true);
                _result[0] = _result[0].Replace("\"", "");
                _result[0] = _result[0].Replace(" ", "");
                _result[0] = StripNewLine(_result[0]);
                _result = GetStringInBetween("<ahref=", "class=fn>", _result[0], false, false);
                _eBookUrl = _result[0];
                Passed = true;
            }
            else
            {
                MessageBox.Show(Resources.PleaseFillInIsbn);
            }

        }

        public void GetBook(string author, string title)
        {
            author = author.ToLower();
            author = author.Replace(" ", "-");
            title = title.ToLower();
            title = title.Replace(" ", "-");

            string url = "http://ebookstore.sony.com/author/" + author + "?keyword=" + author + "&page=1&perpage=100&sortDirection=0";

            if (url != "http://ebookstore.sony.com/search?keyword=")
            {
                var request =
                               (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent =
    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; " +
    "Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; " +
    ".NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; " +
    "InfoPath.2; OfficeLiveConnector.1.3; OfficeLivePatch.0.0)";

                Response = request.GetResponse();
                Stream = Response.GetResponseStream();
                Reader = new StreamReader(Stream);

                string eBookSearch = Reader.ReadToEnd();

                if (eBookSearch.Contains("<div class=\"warning\">"))
                {
                    MessageBox.Show(Resources.CouldNotFindEBookPleaseCheckIfSuppliedAuthorAndTitleIsCorrect);
                    return;
                }

                _result = GetStringInBetween("<a href=\"http://ebookstore.sony.com/ebook/" + author + "/" + title + "/_/", "class=\"fn\">", eBookSearch, false, false);
                _result[0] = _result[0].Replace("\"", "");
                _result[0] = _result[0].Replace(" ", "");
                _result[0] = _result[0].Replace(@"\", "");
                _eBookUrl = "http://ebookstore.sony.com/ebook/" + author + "/" + title + "/_/" + _result[0];
                Passed = true;
            }
            else
            {
                MessageBox.Show(Resources.PleaseFillInAuthorAndBookTitle);
            }

        }

        public void GetInfo()
        {
            if (_eBookUrl != null)
            {
                var fileStream = File.OpenRead(_fDialog.FileName);
                using (var reader = new StreamReader(fileStream))
                {
                    _fileContent = reader.ReadToEnd();
                    reader.Close();
                }

                var infoForm = new InfoForm();

                var request =
                               (HttpWebRequest)WebRequest.Create(_eBookUrl);
                request.UserAgent =
    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; " +
    "Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; " +
    ".NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; " +
    "InfoPath.2; OfficeLiveConnector.1.3; OfficeLivePatch.0.0)";

                Response = request.GetResponse();
                Stream = Response.GetResponseStream();
                Reader = new StreamReader(Stream);

                var eBookSource = Reader.ReadToEnd();
                var information = new StringBuilder(_fileContent);

                //Cover
                if (_fileContent.Contains("%Cover%"))
                {
                    _result = GetStringInBetween("<p id=\"zoom\">", "\">", eBookSource, false, false);
                    _result[0] = StripNewLine(_result[0]);
                    var tempCover = GetStringInBetween("<a href=\"", ".png", _result[0], false, true);
                    var bookCover = tempCover[0];
                    information.Replace("%Cover%", bookCover);
                }

                //Author
                if (_fileContent.Contains("%Author%"))
                {
                    _result = GetStringInBetween("<div class=\"first-child author-section\">", "</h3>", eBookSource, false, false);
                    var author = StripNewLine(_result[0]);
                    author = StripHtml(author);
                    information.Replace("%Author%", author);
                }

                //Title
                if (_fileContent.Contains("%Title%"))
                {
                    _result = GetStringInBetween("<span class=\"fn\">", "</span>", eBookSource, false, false);
                    var title = _result[0];
                    information.Replace("%Title%", title);
                }

                //Publisher
                if (_fileContent.Contains("%Publisher%"))
                {
                    _result = GetStringInBetween("<p class=\"fn\">", "</p>", eBookSource, false, false);
                    var publisher = _result[0];
                    information.Replace("%Publisher%", publisher);
                }

                //Published Date
                if (_fileContent.Contains("%PublishedDate%"))
                {
                    _result = GetStringInBetween("<h3>Publish Date</h3>", "&nbsp;", eBookSource, false, false);
                    var publishedDate = StripNewLine(_result[0]);
                    publishedDate = StripHtml(publishedDate);
                    information.Replace("%PublishedDate%", publishedDate);
                }

                //Print ISBN
                if (_fileContent.Contains("%PrintIsbn%"))
                {
                    _result = GetStringInBetween("<h3>Print ISBN</h3>", "</p>", eBookSource, false, false);
                    var printIsbn = StripNewLine(_result[0]);
                    printIsbn = StripHtml(printIsbn);
                    information.Replace("%PrintIsbn%", printIsbn);
                }

                //eBook ISBN
                if (_fileContent.Contains("%eBookIsbn%"))
                {
                    _result = GetStringInBetween("<h3>eBook ISBN</h3>", "</p>", eBookSource, false, false);
                    var eBookIsbn = StripNewLine(_result[0]);
                    eBookIsbn = StripHtml(eBookIsbn);
                    information.Replace("%eBookIsbn%", eBookIsbn);
                }

                //Filesize
                if (_fileContent.Contains("%Filesize%"))
                {
                    _result = GetStringInBetween("<h3>Filesize</h3>", "</p>", eBookSource, false, false);
                    var fileSize = StripNewLine(_result[0]);
                    fileSize = StripHtml(fileSize);
                    information.Replace("%Filesize%", fileSize);
                }

                //Number of Pages
                if (_fileContent.Contains("%NumberOfPages%"))
                {
                    _result = GetStringInBetween("<h3>Number of Print Pages*</h3>", "</p>", eBookSource, false, false);
                    var numOfPages = StripNewLine(_result[0]);
                    numOfPages = StripHtml(numOfPages);
                    information.Replace("%NumberOfPages%", numOfPages);
                }

                //Description
                if (_fileContent.Contains("%Description%"))
                {
                    _result = GetStringInBetween("<div class=\"content\">", "</div>", eBookSource, false, false);
                    var description = _result[0];
                    description = StripHtml(description);
                    information.Replace("%Description%", description);
                }

                infoForm.infoBox.Text = information.ToString();
                infoForm.Show();

                if (Reader != null)
                    Reader.Close();

                if (Stream != null)
                    Stream.Close();

                if (Response != null)
                    Response.Close();
            }
            else
            {
                if (Passed)
                {
                    MessageBox.Show(Resources.UnableToGetInformationOnBook);
                }
            }
        }

    }
}
